from django.db import models

#newly added imports
from hmac import new as hmac
import base64
from Crypto.Cipher import AES
from Crypto.Hash import SHA256 as sha256

BLOCK_SIZE = 32
# the character used for padding--with a block cipher such as AES, the value
# you encrypt must be a multiple of BLOCK_SIZE in length.  This character is
# used to ensure that your value is always a multiple of BLOCK_SIZE
PADDING = '{'

# one-liner to sufficiently pad the text to be encrypted
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING

# one-liners to encrypt/encode and decrypt/decode a string
# encrypt with AES, encode with base64
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
  
class TwitterUser(models.Model):

    
    userName = models.CharField(max_length=100)
    oauthToken = models.CharField(max_length=256)
    oauthSecret = models.CharField(max_length=512)
    oauthService = models.CharField(max_length=1024)
    dateCreated = models.DateTimeField('Date created')
    
    def create_aes(self, self_key):
        data = hmac(
            str(self.userName), str(self_key), sha256).digest()
        return AES.new(data[:32], AES.MODE_CBC, data[32:32])
 
    def encrypt(self, self_key):
        self.oauthToken = EncodeAES(self.create_aes(str(self_key)) , str(self.oauthToken))
        self.oauthSecret = EncodeAES(self.create_aes(str(self_key)), str(self.oauthSecret))
    
    def decrypt(self, self_key):
        self.oauthToken = DecodeAES(self.create_aes(str(self_key)), self.oauthToken)
        self.oauthSecret = DecodeAES(self.create_aes(str(self_key)), self.oauthSecret)
        
    
    def __unicode__(self):
        return self.userName
